<?php
function req($method, $path, $user, $pass, $body = null)
{
    $ch = curl_init("https://core.spreedly.com$path");
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_USERPWD => $user . ':' . $pass,
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        CURLOPT_POSTFIELDS => $body ? json_encode($body) : null,
    ]);
    $r = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return [$code, json_decode($r, true) ?: $r];
}

//[$c1, $r1] = req('GET', "/v1/payment_methods/{PM_TOKEN}.json", '{ENV_KEY}', '{ACCESS_SECRET}');
//echo "PM exists? HTTP=$c1 storage_state=" . ($r1['payment_method']['storage_state'] ?? 'N/A') . PHP_EOL;

[$c2, $r2] = req('GET', "/v1/gateways.json", '44334FZM998SNV5PP1VNKCHZ93', '{ACCESS_SECRET}');
$hasGw = is_array($r2['gateways'] ?? null) && array_filter($r2['gateways'], fn($g) => $g['token'] === '{GW_TOKEN}');
echo "Gateway in env? " . ($hasGw ? 'YES' : 'NO') . PHP_EOL;

exit(0);

$purchase = ['transaction' => [
    'payment_method_token' => '{PM_TOKEN}', // 若你想测两步法
    'amount' => 1000, 'currency_code' => 'USD'
]];
[$c3, $r3] = req('POST', "/v1/gateways/{GW_TOKEN}/purchase", '{ENV_KEY}', '{ACCESS_SECRET}', $purchase);
echo "Purchase HTTP=$c3 ok=" . (($r3['transaction']['succeeded'] ?? false) ? 'true' : 'false') . PHP_EOL;
if (($r3['errors'][0]['key'] ?? null)) print_r($r3['errors'][0]);
